/*
   Copyright 2008, Andres Postiglioni

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.aconcagua.samples.charts.state {
  import com.aconcagua.samples.charts.state.model.Series;
  import com.aconcagua.samples.charts.state.model.Slider;
  import com.aconcagua.samples.charts.state.model.model;

  import flash.events.Event;
  import flash.events.EventDispatcher;

  import mx.collections.ArrayCollection;
  import mx.events.CollectionEvent;

  /**
   * @author Andres Postiglioni
   */
  public class ApplicationState extends EventDispatcher {
    private var _series: ArrayCollection;
    private var _slider: Slider;

    public function ApplicationState() {
      _series = this.createArrayCollection(refreshSeriesBinding);
    }

    /* Bindable properties */

    [Bindable("series_changed")]
    public function get series(): ArrayCollection {
      return _series;
    }

    [Bindable("slider_changed")]
    public function get slider(): Slider {
      return _slider;
    }

    /* Model update functions */

    model function refreshSeries(newSeries: ArrayCollection): void {
      _series = newSeries;
      this.refreshSeriesBinding(null);
    }

    model function addSeries(series: Series): void {
      _series.addItem(series);
    }

    model function setSlider(theSlider: Slider): void {
      _slider = theSlider;
      this.dispatchEvent(new Event("slider_changed"));
    }

    /* Private functions */

    private function refreshSeriesBinding(event: CollectionEvent): void {
      this.dispatchEvent(new Event("series_changed"));
    }

    //TODO: Move to a helper class
    private function createArrayCollection(changeHandler: Function): ArrayCollection {
      var collection: ArrayCollection = new ArrayCollection();
      collection.addEventListener(
        CollectionEvent.COLLECTION_CHANGE,
        refreshSeriesBinding
      );

      return collection;
    }
  }
}